import { useState, useEffect, useCallback, forwardRef, useImperativeHandle } from 'react';
import moment from 'moment';
import { cloneDeep } from 'lodash';
import { Card, Ellipsis, InfiniteScroll, SpinLoading } from 'antd-mobile';
import { TextWidget } from '@inbiz/react';
import { useInbizRouter } from '@inbiz/hooks';
import { InbizIcon } from '@inbiz/utils';
import {
  getToMe,
  getMyToDo,
  getMyApply,
  getHaveDone,
  getClassification,
  getMyApplying,
} from '../service';
import CardTitle from './components/CardTitle';
import CardExtra from './components/CardExtra';
import Opetations from './components/Operations';
import Avatar from '../Avatar';
import NoData from '../NoData/ListNoData';
import { jumpTo, getFormData } from '../utils';
import { goto, getSummary, getProcessInfoAfterCustomClickItem } from '../../commonUtils';
import './index.less';

const ProcessTodo = forwardRef((props: any, ref) => {
  const { choosedTabKey, userInfo, rangeConfig, processGroup, searchValue, customClickItem } = props;

  const [processData, setProcessData] = useState<any[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [hasMore, setHasMore] = useState<boolean>(true);
  const [requestDone, setRequestDone] = useState(false);
  const [page, setPage] = useState(1);
  const [selectItem, setSelectItem] = useState<any[]>(localStorage.getItem('inbiz-process-center-selectItem') ? JSON.parse(localStorage.getItem('inbiz-process-center-selectItem') || '') : []);
  const router = useInbizRouter();

  let pageCheck = null;

  const formatServer = (
    pageIndex: number,
    data: {
      total: number; rows: any[]
    } = { rows: [], total: 0 },
  ) => {
    setRequestDone(true);
    const state = data !== null;
    let row: any[] = [];
    let checkDataIsNull: boolean | number = false;
    let changeArr: any[] = [];
    let isAdd = false;

    const nowPage = pageIndex;
    if (state) {
      // 判断请求是否成功
      row = data.rows.map((item) => {
        return {
          ...item,
          summary:
            item.summary && item.summary.startsWith('<')
              ? getSummary(item.summary)
              : item.summary,
        };
      });
      checkDataIsNull = row.length && row.length < 1; // 判断是否有数据
      pageCheck = () => {
        // 处理数据
        if (checkDataIsNull) {
          setHasMore(false);
        } else {
          const more = pageIndex < Math.ceil(data.total / 20);
          changeArr = row;
          setHasMore(more);
          setPage(nowPage + 1);
        }
      };
      // 判断页面为1
      if (nowPage == 1) {
        pageCheck();
      } else {
        isAdd = true;
        pageCheck();
      }
      if (isAdd) {
        // 判断是不是有分页数据
        let _processData = processData;
        setProcessData([..._processData, ...changeArr]);
      } else {
        setProcessData(changeArr);
      }
    } else {
      if (pageIndex == 1) {
        setProcessData([]);
      }
    }
  };

  const getList = async (
    value: string,
    pageIndex: number,
    theTabKey: string,
    searchC?: any,
  ) => {
    if (!requestDone) {
      setLoading(true);
    }
    let arr: any[] = [];
    let res: any = {};
    let result: any = { total: 0, rows: [] };
    let _param: any = {
      ...getFormData(userInfo, pageIndex, value || localStorage.getItem('inbiz-process-center-searchValue') || '', searchC),
      dptKey:
        rangeConfig == 'all' || processGroup?.selectedRows?.length == 0
          ? ''
          : processGroup?.groupGuid ?? '',
    }
    if (theTabKey == '3') {
      _param['isunderApplication'] = true;
    };
    if (theTabKey == '6') {
      _param['isunderApplication'] = false;
    };
    switch (theTabKey) {
      case '2':
        res = await getMyToDo(_param);
        if (res && res?.details && res?.details?.rows?.length > 0) {
          arr = res.details.rows.map((item: { taskState: any; taskAssignee: any; taskCreateTime: any; }) => ({
            ...item,
            taskState: item.taskState ?? '0',
            checked: false,
            starter: item.taskAssignee,
            processTime: item.taskCreateTime,
          }));
          res.details.rows = arr;
          result = res.details;
        }
        break;
      case '3':
        res = await getMyApplying(_param);
        if (res && res.details && res.details.rows.length > 0) {
          arr = res.details.rows.map((item: { taskState: any; processState: any; processStartTime: any; }) => ({
            ...item,
            taskState: item.taskState || item.processState || 0,
            checked: false,
            starter: userInfo.ID,
            processTime: item.processStartTime,
          }));
          res.details.rows = arr;
          result = res.details;
        }
        break;
      case '5':
        res = await getToMe(_param);
        if (res && res.details && res.details.rows.length > 0) {
          arr = res.details.rows.map((item: { taskState: string; taskAssignee: any; taskStartTime: any; }) => ({
            ...item,
            taskState:
              item.taskState == '170' || item.taskState == '180'
                ? item.taskState ?? '0'
                : '150',
            checked: false,
            starter: item.taskAssignee,
            processTime: item.taskStartTime,
          }));
          res.details.rows = arr;
          result = res.details;
        }
        break;
      case '6':
        res = await getMyApply(_param);
        if (res && res.details && res.details.rows.length > 0) {
          arr = res.details.rows.map((item: { taskState: any; processState: any; processStartTime: any; }) => ({
            ...item,
            taskState: item.taskState || item.processState || 0,
            checked: false,
            processTime: item.processStartTime,
          }));
          res.details.rows = arr;
          result = res.details;
        }
        break;
      case '7':
        res = await getHaveDone(_param);
        if (res && res.details && res.details.rows.length > 0) {
          arr = res.details.rows.map((item: { taskState: any; processState: any; initiatorName: any; taskCreateTime: any; }) => ({
            ...item,
            taskState: item.taskState || item.processState || 0,
            checked: false,
            starter: item.initiatorName,
            processTime: item.taskCreateTime,
          }));
          res.details.rows = arr;
          result = res.details;
        }
        break;
      case '8':
        res = await getClassification(_param);
        if (res && res.details && res.details.rows.length > 0) {
          arr = res.details.rows.map((item: { taskState: any; processState: any; initiatorName: any; processCreateTime: any; }) => ({
            ...item,
            taskState: item.taskState || item.processState || 0,
            checked: false,
            starter: item.initiatorName,
            processTime: item.processCreateTime,
          }));
          res.details.rows = arr;
          result = res.details;
        }
        break;
      default:
        break;
    }
    formatServer(pageIndex, result);
    setLoading(false);
  };

  const changeBox = (checked: boolean, item: { taskId: string }) => {
    let _selectItem = cloneDeep(selectItem);
    if (checked) {
      _selectItem?.push(item?.taskId)
    } else {
      _selectItem = _selectItem?.filter((item1: any) => item1 != item?.taskId)
    }
    setSelectItem(_selectItem);
    localStorage.setItem('inbiz-process-center-selectItem', JSON.stringify(_selectItem));
  };

  useEffect(() => {
    setSelectItem(localStorage.getItem('inbiz-process-center-selectItem') ? JSON.parse(localStorage.getItem('inbiz-process-center-selectItem') || '') : []);
    getList('', 1, choosedTabKey, localStorage.getItem('inbiz-process-center-filterTab') ? JSON.parse(localStorage.getItem('inbiz-process-center-filterTab') || '') : {});
  }, [choosedTabKey, rangeConfig]);

  useImperativeHandle(ref, () => ({
    getList: async (text: string, condition?: any) => {
      setSelectItem([]);
      getList(text, 1, choosedTabKey, condition);
    },
    setSelectItem,
  }));

  return (
    <div className={'processTodo'}>
      {loading ? (
        <div className={'loading'}>
          <SpinLoading />
        </div>
      ) : processData?.length > 0 ? (
        <>
          {processData.map((item: any, index: number) => {
            return (
              <Card
                className={'toDoContainer'}
                title={<CardTitle data={item} choosedTabKey={choosedTabKey} />}
                extra={
                  choosedTabKey == '2' && (
                    <CardExtra data={item} changeBox={changeBox} selectItem={selectItem} />
                  )
                }
                key={(item.taskId || item.processInstanceId) + choosedTabKey || ''}
              >
                <header
                  className={'cardHeader'}
                  onClick={async (e) => {
                    if (customClickItem) {
                      const result = await getProcessInfoAfterCustomClickItem({
                        processInstanceId: item.processInstanceId,
                        starter: item.taskAssignee,
                        taskIds: item.taskId,
                        taskState: item.taskState,
                        inItiateApplication: false,
                        siteType: 1,
                      });
                      customClickItem({ event: e, processItem: item, requestItem: result });
                    } else {
                      goto(
                        {
                          processInstanceId: item.processInstanceId,
                          starter: item.taskAssignee,
                          taskIds: item.taskId,
                          taskState: item.taskState,
                          inItiateApplication: false,
                          siteType: 1,
                        },
                        choosedTabKey, 'wap', e, '',
                        () => {
                          getList('', 1, choosedTabKey);
                        },
                        // setLoading,
                      );
                    }
                  }}
                >
                  {choosedTabKey !== '3' && choosedTabKey !== '6' && (
                    <Avatar userId={item.userId} style={{ width: 40, height: 40 }} />
                  )}
                  <p>
                    <h4
                      className={'userName'}
                      title={item.initiatorName || item.initiatorName}
                    >
                      {' '}
                      {item.initiatorName || item.starterName}
                    </h4>
                    {typeof item.summary === 'string' && item.summary.trim() !== '' && (
                      <p className={'summary'} title={item.summary}>
                        <Ellipsis direction="end" rows={2} content={item.summary} />
                      </p>
                    )}
                  </p>
                </header>
                <section
                  className={'cardBody'}
                  onClick={async (e) => {
                    if (customClickItem) {
                      const result = await getProcessInfoAfterCustomClickItem({
                        processInstanceId: item.processInstanceId,
                        starter: item.taskAssignee,
                        taskIds: item.taskId,
                        taskState: item.taskState,
                        inItiateApplication: false,
                        siteType: 1,
                      });
                      customClickItem({ event: e, processItem: item, requestItem: result });
                    } else {
                      goto(
                        {
                          processInstanceId: item.processInstanceId,
                          starter: item.taskAssignee,
                          taskIds: item.taskId,
                          taskState: item.taskState,
                          inItiateApplication: false,
                          siteType: 1,
                        },
                        choosedTabKey,
                        'wap',
                        e,
                        '',
                        () => {
                          getList('', 1, choosedTabKey);
                        },
                        // setLoading,
                      );
                    };
                  }}
                >
                  <p>
                    <TextWidget>processCenter.instanceNumber</TextWidget>:{' '}
                    {item.processInstanceId}
                  </p>
                  <p>{moment(item.processTime).format('YYYY-MM-DD HH:mm:ss')}</p>
                </section>
                <section className={'cardFooter'}>
                  <p
                    style={{ color: 'var(--inbiz-color-primary)' }}
                    onClick={() => jumpTo(item, router)}
                  >
                    <InbizIcon
                      type="icon-process-liuchengrizhi"
                      style={{ color: 'var(--inbiz-color-primary)', fontSize: 12 }}
                    />
                    <span style={{ marginLeft: 5 }}>
                      <TextWidget>processCenter.processLog</TextWidget>
                    </span>
                  </p>
                  <p
                    onClick={async (e) => {
                      if (customClickItem) {
                        const result = await getProcessInfoAfterCustomClickItem({
                          processInstanceId: item.processInstanceId,
                          starter: item.taskAssignee,
                          taskIds: item.taskId,
                          taskState: item.taskState,
                          inItiateApplication: false,
                          siteType: 1,
                        });
                        customClickItem({ event: e, processItem: item, requestItem: result });
                      } else {
                        goto(
                          {
                            processInstanceId: item.processInstanceId,
                            starter: item.taskAssignee,
                            taskIds: item.taskId,
                            taskState: item.taskState,
                            inItiateApplication: false,
                            siteType: 1,
                          },
                          choosedTabKey,
                          'wap',
                          e,
                          '',
                          () => {
                            getList('', 1, choosedTabKey);
                          },
                          // setLoading,
                        );
                      }
                    }}
                  >
                    <TextWidget>processCenter.lookDetails</TextWidget>
                  </p>
                </section>
              </Card>
            );
          })}
          <InfiniteScroll loadMore={() => getList('', page, choosedTabKey)} hasMore={hasMore} />
          {choosedTabKey == '2' && (
            <Opetations
              setLoading={setLoading}
              selectItem={selectItem}
              list={processData}
              $selectItem={setSelectItem}
            />
          )}
        </>
      ) : (
        <>
          <NoData />
          {choosedTabKey == '2' && (
            <Opetations
              setLoading={setLoading}
              selectItem={selectItem}
              list={processData}
              $selectItem={setSelectItem}
            />
          )}
        </>
      )}
    </div>
  );
});

export default ProcessTodo;
